package com.forlove.app.common.utils;


import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


public class CryptAES {

    private static final String AESTYPE = "AES/ECB/PKCS7Padding";

    public static String AES_Encrypt(String keyStr, String plainText) {
        byte[] encrypt = null;
        try {
            Key key = generateKey(keyStr);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encrypt = cipher.doFinal(plainText.getBytes("UTF-8"));
            return new String(android.util.Base64.encode(encrypt, 0), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String AES_Decrypt(String keyStr, String encryptData) {
        byte[] decrypt = null;
        try {
            Key key = generateKey(keyStr);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            decrypt = cipher.doFinal(android.util.Base64.decode(encryptData.getBytes("UTF-8"), 0));
            return new String(decrypt, "UTF-8").trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Key generateKey(String key) throws Exception {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            return keySpec;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    public static void main(String[] args) throws Exception {
        String keyStr = CipherUtils.md5("1502123331320171103");
        String plainText = "15021233313";
        String encText = AES_Encrypt(keyStr, plainText);
        String decString = AES_Decrypt(keyStr, encText);
        System.out.println("秘钥：" + keyStr);
        System.out.println("明文：" + plainText);
        System.out.println("密文：" + encText);
        System.out.println("解密：" + decString);


    }
}